/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.ui.client.actions;

import static org.opu.pc.ui.client.widgets.TableRenderPublisher.COLUMN_NAMES;
import static org.opu.pc.ui.client.widgets.TableRenderPublisher.TYPES;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.JTextComponent;
import org.opu.pc.domain.domains.security.SecurityGroup;
import org.opu.pc.security.Secured;

import org.opu.pc.services.beans.PublicationBean;
import org.opu.pc.services.beans.PublisherBean;
import org.opu.pc.ui.client.MainToolBar;
import org.opu.pc.ui.client.widgets.PropertiesEditPane;
import org.opu.pc.ui.client.widgets.TabelBeanView;
import org.opu.pc.ui.client.widgets.TableRenderPublisher;
import org.opu.pc.ui.util.GUIUtils;
import org.opu.pc.ui.util.GUIUtils.ActionListener;

/**
 * 
 * @author yura
 */
@Secured(SecurityGroup.Professor)
public class NewPublication extends PublicationSearch {

	public static final String PUBLICATION_DATE = "date";
	private static final int LINE_NUMBER = 10;

	private static final long serialVersionUID = -3157205013053013023L;
	
	private TabelBeanView table;
    private TableRenderPublisher tableRender = new TableRenderPublisher();
    
    // this pane is initialized when abstract dialog action call "okAction" method
    PropertiesEditPane propertiesEditPane;

	@Override
	public String getName() {
		return "NewPublication";
	}

    @Override
    protected void appendDate(LinkedHashMap<String, Object> properties) {
        properties.put(PUBLICATION_DATE, (Date)null);
    }

	@Override
	protected void addPropertiesPane(JPanel cp, PropertiesEditPane pane) {
		table = createTable(new ArrayList<PublisherBean>());
		JPanel tablePanel = new JPanel(new BorderLayout());
		tablePanel.add(new JScrollPane(table), BorderLayout.CENTER);
		tablePanel.add(createEastPublisherPanel(table), BorderLayout.EAST);
		
		JComponent b;
        // simple makeup
//        b = Box.createVerticalBox();
//		b.add(inBordePanel(i18n.getSafe("publication.new.properties") + ": ",
//                pane, false));
//		b.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE_HALF));
//		b.add(inBordePanel(i18n.getSafe("publication.new.publishers") + ": ",
//                tablePanel, true));
//		b.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE_HALF));
//		b.add(inBordePanel(i18n.getSafe("publication.new.file") + ": ",
//                new FileChoosePanel(), true));

        // Split makeup
        JSplitPane splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                inBordePanel("publication.new.publishers", tablePanel, true), 
                inBordePanel("publication.new.file", new FileChoosePanel(), true));
        splitPane1.setResizeWeight(0.99);
        splitPane1.setOneTouchExpandable(true);
        splitPane1.setContinuousLayout(true);
        splitPane1.setDividerSize(4);
        
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                inBordePanel("publication.new.properties", pane, false), 
                splitPane1);
        b = splitPane;
        splitPane.setDividerSize(4);

		cp.add(b);
	}
	
	private JPanel inBordePanel(String title, JComponent comp, boolean space){
        title = i18n.getSafe(title);
		JPanel pane1 = new JPanel(new BorderLayout());
		pane1.setBorder(BorderFactory.createTitledBorder(title));
		if (space) {
			comp = GUIUtils.hBorder(comp);
		}
		pane1.add(comp, BorderLayout.CENTER);
		return pane1;
	}

	@Override
	protected int getMinimalDialogWidth() {
		return 600;
	}
	
	@Override
	protected Boolean getAppliedBool(Map<String, Object> prop) {
		Boolean bool = super.getAppliedBool(prop);
		return bool != null ? bool.booleanValue() : false;
	}

	@Override
	protected OkAction getOkAction(JDialog dialog, PropertiesEditPane pane) {
		propertiesEditPane = pane;
		return new OkAction(pane, dialog) {

			private static final long serialVersionUID = 8463973341685199259L;

			@Override
			public void runAction(ActionEvent e) throws Exception {
				Map<String, Object> prop = pane.getProperties();
				publicationService.createNew(
						new PublicationBean(-1, 
								NewPublication.this.getName(prop),
                                (String)prop.get(PUBLICATION_PUBLICATIONPLACE),
                                (Date)prop.get(PUBLICATION_DATE),
                                (String)prop.get(PUBLICATION_CONFERENCE_VENUE),
                                (Integer)prop.get(PUBLICATION_PAGE_NUMBER_START),
                                (Integer)prop.get(PUBLICATION_PAGE_NUMBER_END),
								NewPublication.this.getAppliedBool(prop)),
						readTable(table));
			}
		};
	}

	@Override
	protected String getCacelActionName() {
		return "Close";
	}
	
	private List<PublisherBean> readTable(TabelBeanView table){
		List<PublisherBean> publishers = new ArrayList<PublisherBean>();
		Object[][] content = table.getContent();
		
		for (int i = 0; i < content.length; i++) {
			Object[] objects = content[i];
			publishers.add(new PublisherBean(-1, 
                    (String)objects[1], // name
					(String)objects[0], // surname
                    (String)objects[2], // middle name
					(Boolean)objects[3]));
		}
		
		return publishers;
	}

    private List<PublisherBean> getExeptSelection(TabelBeanView table) {
        int[] indexes = table.getSelectedIndexes();
        List<PublisherBean> model = readTable(table);
        if (indexes == null || indexes.length < 1){
            return model;
        }

        List<PublisherBean> selection = new ArrayList<PublisherBean>();
        Set<Integer> set = new HashSet<Integer>();
        for (int integer : indexes) {
            set.add(integer);
        }

        for (int i = 0; i < model.size(); i++) {
            if (!set.contains(i)) {
                selection.add(model.get(i));
            }
        }

        return selection;
    }

	private TabelBeanView createTable(List<PublisherBean> publishers) {
		TabelBeanView tbl = new TabelBeanView(new Object[0][4], TYPES, COLUMN_NAMES);
        tableRender.rendView(publishers, tbl);
		tbl.setEditable(true);
		tbl.setSize(400, 400);
		return tbl;
	}

	private JComponent createEastPublisherPanel(final TabelBeanView table) {
		Box panel = Box.createVerticalBox();
		panel.add(Box.createVerticalGlue());
		panel.add(initSmallBtn(GUIUtils.getAction("Plus", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) throws Exception {
                List<PublisherBean> readTable = readTable(table);
                readTable.add(new PublisherBean());
                tableRender.rendView(readTable, table);
            }
		}, true)));
		panel.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE_HALF / 2));
		panel.add(initSmallBtn(GUIUtils.getAction("Minus", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                List<PublisherBean> exeptSelection = getExeptSelection(table);
                tableRender.rendView(exeptSelection, table);
            }
		}, true)));
		panel.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE_HALF / 2));
		return panel;
	}

    private JComponent initSmallBtn(AbstractAction action) {
        JButton btn = new JButton(action);
        btn.setMaximumSize(new Dimension(24, 24));
        btn.addMouseListener(MainToolBar.MOUSE_LISTENER);
        btn.setContentAreaFilled(false);
        btn.setBorderPainted(false);
        return btn;//GUIUtils.hBorder(btn, 6, 1);
    }

	class FileChoosePanel extends JPanel {

		private static final long serialVersionUID = 8706763798095671715L;
		
		JTextField field = GUIUtils.addActions(new JTextField());
        JTextComponent texts = GUIUtils.addActions(new JTextArea(10, 30));
        JScrollPane textsPane = new JScrollPane(texts);
		File file;
        private boolean textNotVisible = true;
		
		public FileChoosePanel() {
			super(new BorderLayout());

			field.setEditable(false);
			field.setBackground(Color.WHITE);
			texts.setBackground(Color.WHITE);
            texts.setFont(new Font(Font.DIALOG_INPUT, Font.PLAIN, 13));
            textsPane.setVisible(false);
            textsPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            textsPane.setMinimumSize(new Dimension(1, 120));

			AbstractAction chooseAction = GUIUtils.getAction("ChoseFile", new ActionListener() {

				public void actionPerformed(ActionEvent arg0) throws Exception {
					JFileChooser c = new JFileChooser();
					c.setMultiSelectionEnabled(false);
			        c.setDialogTitle(getDialogTitle());
			        for(String str :publicationService.getDocumentExtensions()){
			        	c.addChoosableFileFilter(new FileNameExtensionFilter(
			        			str, str));
			        }
					int rVal = c.showOpenDialog(null);
					if (rVal == JFileChooser.APPROVE_OPTION) {
						file = c.getSelectedFile();
						field.setText(file.getAbsolutePath());
						textsPane.setVisible(true);
						PublicationBean bean = new PublicationBean();
						ArrayList<PublisherBean> list = new ArrayList<PublisherBean>();
						StringBuffer buffer = new StringBuffer();
						publicationService.analysFile(bean, list, file, buffer, LINE_NUMBER);
						texts.setText(buffer.toString());
                        texts.setCaretPosition(0);
						tableRender.rendView(list, table);
						propertiesEditPane.set(PUBLICATION_NAME, bean.getName());
						propertiesEditPane.set(PUBLICATION_DATE, new Date());
						propertiesEditPane.set(PUBLICATION_APPLIED, true);
						FileChoosePanel.this.revalidate();
                        if (textNotVisible) {
                            textNotVisible = false;
                            ((JSplitPane) FileChoosePanel.this.getParent()
                                    .getParent().getParent()).resetToPreferredSizes();

                            SwingUtilities.invokeLater(new Runnable() {

                                public void run() {
                                    textsPane.setMinimumSize(new Dimension(1, 20));
                                }
                            });
                        }
					}
				}
			});
			chooseAction.mainView = NewPublication.this.mainView;

            Box b = Box.createHorizontalBox();
            b.add(new JButton(chooseAction));

            JPanel p2 = new JPanel(new BorderLayout(GUIUtils.DEFAULT_SPACE_HALF,
                    GUIUtils.DEFAULT_SPACE_HALF));
            p2.add(field, BorderLayout.CENTER);
            p2.add(b, BorderLayout.EAST);

			add(p2, BorderLayout.NORTH);
            add(textsPane, BorderLayout.CENTER);
		}
	}
}
